package com.example.readbook.Adapter

import android.support.v7.widget.RecyclerView
import java.util.*

/**
 * Package    : com.zjedu.function.Adapter
 * ClassName  : BaseAdapter
 * Description: $Adapter基类
 */
abstract class BaseAdapter<L>(var l: MutableList<L>) : RecyclerView.Adapter<RecyHolder>() {

    //更新数组
    open fun updateList(list: List<L>) {
        l.clear()
        l.addAll(list)
        notifyDataSetChanged()
    }

    //获取一个指定位置的Item
    fun getItemAtPosition(posi: Int): L {
        return l[posi]
    }

    //更新制定位置Item
    fun updateItem(posi: Int, date: L) {
        l[posi] = date
        notifyItemChanged(posi)
    }

    //移除一个Item 防止崩溃
    fun remove(position: Int, isNull: (list: MutableList<L>) -> Unit) {
        l.removeAt(position)
        notifyItemRemoved(position)
        // 如果移除的是最后一个，忽略
        if (position != l.size)
            notifyItemRangeChanged(position, l.size - position)
        isNull.invoke(l)
    }

    //批量移除
    fun remove(list: MutableList<Int>, isNull: (list: MutableList<L>) -> Unit) {
        list.sortWith(Comparator { o1, o2 ->
            return@Comparator Integer.compare(o1, o2)
        })

        for (i in 0 until list.size) {
            var posi = list[i]
            posi -= i
            remove(posi) {}
        }
        isNull.invoke(l)
    }
}